# encoding:utf-8
"""
@file = role_manage
@author = zouju
@create_time = 2023-09-13- 8:41
"""
from django.shortcuts import render
from rest_framework.decorators import api_view

from common.API import res_josn_data
from common.API.log import exec_log
from common.authentication.jwt_auth import jwt_login_required
from common.layuiview.layuiviewsets import ModelViewSetLayui
from system_manage.models import Role, Power, User, RolePower
from system_manage.serializers import RoleModelSerializer


def role_manage_page(request):
    return render(request, 'sys_manage/role_manage/role_main.html')


def role_add_page(request):
    return render(request, 'sys_manage/role_manage/role_add.html')


def role_power_page(request):
    return render(request, 'sys_manage/role_manage/role_power.html')


@api_view(['POST'])
@jwt_login_required
def role_power_query(request):
    data_list = []
    post_data = request.POST
    print('table.render数据:', post_data)
    role_id = post_data.get('role_id', None)
    user_id = post_data.get('user_id', None)
    cur_user_role = User.objects.filter(id_number=user_id).first()

    # 获取当前用户的所有权限
    cur_user_obj = RolePower.objects.values_list('power_id').filter(role_id=cur_user_role.role_id)
    cur_usr_id_list = [i[0] for i in cur_user_obj]
    # 获取当前选择角色的所有权限
    power_id_obj = RolePower.objects.values_list('power_id').filter(role_id=role_id)
    power_id_list = [item[0] for item in power_id_obj]
    # print(cur_user_obj, power_id_list)
    # 目录对象
    power_dir_obj = Power.objects.filter(type=1).order_by('sort')

    for item_dir in power_dir_obj:
        if item_dir.id in cur_usr_id_list:
            dir_id = item_dir.id
            power_menu_obj = Power.objects.filter(parent_id=dir_id).order_by('sort')  # 通过目录id获取菜单对象
            data_list1 = []
            for item in power_menu_obj:
                if item.id in cur_usr_id_list:
                    button_checkbox_list = []
                    if item.id in power_id_list:
                        power_check = 'checked'
                    else:
                        power_check = ''
                    button_obj = Power.objects.filter(parent_id=item.id).order_by('sort')  # 通过菜单id获取按钮对象
                    power_name_list = [i.name for i in button_obj]
                    button_id_list = [i.id for i in button_obj]
                    # 判断按钮是否被选中
                    for button_id in button_id_list:
                        if button_id in power_id_list:
                            button_check = 'checked'
                        else:
                            button_check = ''
                        button_checkbox_list.append(button_check)

                    item_data1 = {
                        "menuId": item.id,
                        "menuName": item.name,
                        "menuCheckbox": power_check,
                        "buttonName": power_name_list,
                        "buttonId": button_id_list,
                        "buttonCheckbox": button_checkbox_list
                    }
                    data_list1.append(item_data1)

            item_data = {
                "dirId": item_dir.id,
                "dirName": item_dir.name,
                "menuInfo": data_list1
            }
            data_list.append(item_data)
    return res_josn_data.table_api(data=data_list, count=len(data_list))


@api_view(['POST'])
@jwt_login_required
def role_power_save(request):
    menu_power_list = []
    button_power_list = []
    post_data = request.POST
    print('role-power-save-data:', post_data)
    role_id = post_data.get('id', '')
    role_name = post_data.get('code', '')
    for item in post_data:
        if item[:4] == 'page':
            page_value = post_data.get(item, '')
            menu_power_list.append(page_value)
        elif item[:6] == 'button':
            button_value = post_data.get(item, '')
            button_power_list.append(button_value)
        else:
            pass
    dir_power = Power.objects.filter(id__in=menu_power_list)
    dir_power_list = [item.parent_id for item in dir_power]
    dir_power_list = list(set(dir_power_list))

    print('目录权限ID:', dir_power_list)
    print('菜单权限ID:', menu_power_list)
    print('按钮权限ID:', button_power_list)

    if role_id is None:
        return res_josn_data.fail_api(msg='role_id为空')

    # 删除原有权限
    RolePower.objects.filter(role_id=role_id).delete()

    # 添加新权限,power_type 1目录 2菜单 3按钮
    for item_id in dir_power_list:
        role_obj = RolePower(role_id=role_id, power_id=item_id, power_type_id='1')
        role_obj.save()
    for item_id in menu_power_list:
        role_obj = RolePower(role_id=role_id, power_id=item_id, power_type_id='2')
        role_obj.save()
    for item_id in button_power_list:
        role_obj = RolePower(role_id=role_id, power_id=item_id, power_type_id='3')
        role_obj.save()
    exec_log(request, is_access=True, desc=f'{role_name} 权限修改成功')
    return res_josn_data.success_api('保存成功')


class RoleGenericView(ModelViewSetLayui):  # 角色视图
    queryset = Role.objects.all()
    serializer_class = RoleModelSerializer
